package com.itheima.mp.controller;

import cn.hutool.core.bean.BeanUtil;
import com.itheima.mp.domain.dto.PageDTO;
import com.itheima.mp.domain.dto.UserFormDTO;
import com.itheima.mp.domain.po.User;
import com.itheima.mp.domain.query.UserQuery;
import com.itheima.mp.domain.vo.UserVO;
import com.itheima.mp.service.IUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * ClassName: UserController
 * Description:
 *
 * @Author HL
 * @Create 2024/7/2 16:07
 * @Version 1.0
 */
@Tag(name = "用户管理接口")
@RestController
@RequestMapping("/users")
@RequiredArgsConstructor
public class UserController {
    private final IUserService userService;

    @Operation(summary = "新增用户接口")
    @PostMapping
    public void saveUser(@RequestBody UserFormDTO UserDTO){
        //1. 把DTO拷贝到PO
        User user = BeanUtil.copyProperties(UserDTO, User.class);
        //2. 新增
        userService.save(user);
    }

    @Operation(summary = "删除用户接口")
    @DeleteMapping("/{id}")
    public void deleteUserById(@Parameter(description = "用户id") @PathVariable Long id){
        userService.removeById(id);
    }

    @Operation(summary = "根据id查询用户接口")
    @GetMapping("/{id}")
    public UserVO queryUserById(@Parameter(description = "用户id") @PathVariable Long id){
        /*//1. 查询用户PO
        User user = userService.getById(id);
        //2. 把PO拷贝到VO
        return BeanUtil.copyProperties(user, UserVO.class);*/
        return userService.queryUserAndAddressById(id);
    }

    @Operation(summary = "根据id批量查询用户接口")
    @GetMapping
    public List<UserVO> queryUserByIds(@Parameter(description = "用户id集合") @RequestParam List<Long> ids){
        /*//1. 查询用户PO
        List<User> users = userService.listByIds(ids);
        //2. 把PO拷贝到VO
        return BeanUtil.copyToList(users, UserVO.class);*/
        return userService.queryUserAndAddressByIds(ids);
    }

    @Operation(summary = "扣减用户余额接口")
    @PutMapping("/{id}/deduction/{money}")
    public void deleteUserById(@Parameter(description = "用户id") @PathVariable Long id,
                               @Parameter(description = "扣减的金额") @PathVariable Integer money){
        userService.deductBalance(id, money);
    }

    @Operation(summary = "根据复杂条件查询用户接口")
    @GetMapping("/list")
    public List<UserVO> queryUsers(UserQuery query){
        //1. 查询用户PO
        List<User> users = userService.queryUsers(query.getName(), query.getStatus(), query.getMinBalance(), query.getMaxBalance());
        //2. 把PO拷贝到VO
        return BeanUtil.copyToList(users, UserVO.class);
    }

    @Operation(summary = "根据条件分页查询用户接口")
    @PostMapping("/page")
    public PageDTO<UserVO> queryUsersPage(@RequestBody UserQuery query){
        return userService.queryUsersPage(query);
    }
}
